﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using MS.InformationManagement.DAL.DTOs;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Support;
using MS.InformationManagement.Presenter.SearchSender;
using Microsoft.SharePoint.Linq;
using MS.InformationManagement.DAL.DocumentCenter;
using System.Linq;
using System.Web;
using Microsoft.SharePoint;
using MS.InformationManagement.Presenter.ConCoipaSelector;


namespace MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls
{
    public partial class ConCoipaSelector : BaseControl, IConCoipaSelectorView
    {
        #region fields

        ConCoipaSelectorPresenter _presenter;

        #endregion

        #region Properties

        public List<ContactsDTO> ContactosList
        {
            get
            {
                if (Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "ContactosList"] == null)
                    Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "ContactosList"] = new List<ContactsDTO>();
                return Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "ContactosList"] as List<ContactsDTO>;
            }
            set
            {
                Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "ContactosList"] = value;
            }
        }
        public bool ShowButtonClose { get; set; }
        public IEnumerable<MedioDeEnvio> MediosDeEnvio { get; set; }
        public int IdCopy
        {
            get
            {
                if (string.IsNullOrEmpty(Page.Request.QueryString["IdCopy"]))
                    return 0;
                else
                    return int.Parse(Page.Request.QueryString["IdCopy"]);
            }
        }
        public string Strategy
        {
            get { return Page.Request.QueryString["strategy"]; }
        }

        #endregion

        #region Form Methods

        protected void Page_Load(object sender, EventArgs e)
        {
            //Cache.Remove(SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "ContactosList");

            string str = string.Empty;
            
            foreach (ContactsDTO ct in ContactosList)
            { 
                str += ct.IdItem + " --" + ct.Nombre;
            }
            if (!IsPostBack)
                BindDataGridResult();
        }

        protected void delete_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                ImageButton currentButton = sender as ImageButton;
                if (currentButton == null) return;
                ContactosList.RemoveAll(x => x.Id == currentButton.CommandArgument);
                Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "ContactosList"] = ContactosList;
                BindDataGridResult();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void edit_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                ImageButton currentButton = sender as ImageButton;

                if (currentButton == null) return;
                GridViewRow row = currentButton.NamingContainer as GridViewRow;
                gvMultiResults.EditIndex = row.RowIndex;

                DropDownList combo = gvMultiResults.Rows[row.RowIndex].FindControl("_ddlEnvio") as DropDownList;
                combo.Enabled = true;

                BindDataGridResult();

            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void update_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                if (this.gvMultiResults.EditIndex != -1)
                {
                    ImageButton currentButton = sender as ImageButton;
                    if (currentButton == null) return;

                    if (ContactosList != null)
                    {
                        GridViewRow row = currentButton.NamingContainer as GridViewRow;
                        DropDownList combo = gvMultiResults.Rows[row.RowIndex].FindControl("_ddlEnvio") as DropDownList;


                        ContactsDTO ContactoEdit = ContactosList[row.RowIndex];
                        ContactoEdit.Id = ((TextBox)(row.Cells[0].Controls[0])).Text;
                        ContactoEdit.Nombre = ((TextBox)(row.Cells[1].Controls[0])).Text;
                        ContactoEdit.Representante = ((TextBox)(row.Cells[2].Controls[0])).Text;
                        ContactoEdit.Direccion = ((TextBox)(row.Cells[3].Controls[0])).Text;
                        ContactoEdit.Telefono = ((TextBox)(row.Cells[4].Controls[0])).Text;
                        ContactoEdit.MedioEnvio = combo.SelectedItem.Text;
                        ContactoEdit.IdMedioEnvio = combo.SelectedItem.Value;
                    }

                    gvMultiResults.EditIndex = -1;
                    Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "ContactosList"] = ContactosList;
                    BindDataGridResult();
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void gvMultiResults_PreRender(object sender, EventArgs e)
        {
            if (this.gvMultiResults.EditIndex != -1)
            {
                TextBox txt = ((TextBox)(gvMultiResults.Rows[gvMultiResults.EditIndex].Cells[2].Controls[0]));
                if (ContactosList != null)
                {
                    ContactsDTO ContactoEdit = ContactosList[gvMultiResults.EditIndex];
                    if (string.IsNullOrEmpty(ContactoEdit.Representante))
                        txt.Visible = false;
                }
            }
        }

        protected void gvMultiResults_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[9].Visible = false;
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Cells[9].Visible = false;

                DropDownList ddl = (DropDownList)e.Row.FindControl("_ddlEnvio");
                ddl.DataSource = MediosDeEnvio;
                ddl.DataTextField = "Title";
                ddl.DataValueField = "Id";
                ddl.DataBind();
            }
        }

        private void SetControlsGrid()
        {
            if (gvMultiResults.Rows.Count > 0)
            {
                btnClose.Visible = ShowButtonClose;
                foreach (GridViewRow row in gvMultiResults.Rows)
                {
                    ImageButton img = (ImageButton)row.FindControl("imgDelete");
                    DropDownList ddl = (DropDownList)row.FindControl("_ddlEnvio");

                    if (Strategy != "UpdateCopy")
                        row.Enabled = false;

                    if (gvMultiResults.EditIndex != row.RowIndex || gvMultiResults.EditIndex == -1)
                    {
                        ddl.Enabled = false;
                        
                        if (IdCopy != 0)
                            row.Enabled = false;

                        if (IdCopy.ToString() == row.Cells[9].Text)
                        {
                            row.Enabled = true;
                            img.Enabled = false;
                        }

                    }
                    else
                        ddl.Enabled = true;

                    if (this.gvMultiResults.EditIndex != -1)
                        row.Enabled = true;
            
                    if (ContactosList.Count > row.RowIndex)
                    {
                        ContactsDTO ContactoEdit = ContactosList[row.RowIndex];
                        if (ContactoEdit != null)
                        {
                            if (!string.IsNullOrEmpty(ContactoEdit.MedioEnvio))
                                ddl.SelectedValue = ContactoEdit.IdMedioEnvio;
                        }
                    }
                }
            }
        }

        #endregion

        #region Implemented Methods

        public void Show()
        {

        }

        public void BindDataGridResult()
        {
            LoadMediosEnvios();
            if (MediosDeEnvio.Count() > 0)
            {
                if (ContactosList != null)
                {
                    SetControlsGrid();
                    gvMultiResults.DataSource = ContactosList;
                    gvMultiResults.DataBind();
                    SetControlsGrid();
                }
            }
            else
            {

                this.HandleWarning("No existen medios de envío cargados");
            }

        }

        public void LoadMediosEnvios()
        {
            _presenter = new ConCoipaSelectorPresenter(this);
            _presenter.HandleLoad();
        }

        #endregion
    }
}
